package me.kagami.extmybatis;

import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;


public class ExtMybatisMain extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {
        VirtualFile file = event.getData(PlatformDataKeys.VIRTUAL_FILE);
        //弹出窗口
        //Messages.showMessageDialog(file.getName(), "Information", Messages.getInformationIcon());
        NotificationGroup notify = new NotificationGroup("extmybatis.notify", NotificationDisplayType.BALLOON, true);
        try {
            File extDir = new File(file.getParent().getPath() + File.separator + "ext");
            if (!extDir.exists()) {
                extDir.mkdir();
            }
            File extMapperXml = new File(extDir.getPath() + File.separator + "Ext" + file.getName());
            extMapperXml.deleteOnExit();
            extMapperXml.createNewFile();

            String nameSpace = getNameSpace(file);
            if (nameSpace == null || nameSpace.equals("")) {
                notify.createNotification("ExtMybatis生成异常", NotificationType.ERROR).notify(event.getProject());
            }
            String packageStr = nameSpace.substring(0, nameSpace.lastIndexOf("."));
            String classNameStr = nameSpace.replace(packageStr + ".", "");
            String packagePatch = packageStr.replaceAll("\\.", Matcher.quoteReplacement(File.separator));


            String basePath = event.getProject().getBasePath();
            File extPackagePatchFile = new File(basePath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + packagePatch + File.separator + "ext");
            if (!extPackagePatchFile.exists()) {
                extPackagePatchFile.mkdir();
            }
            String extClassStr = "Ext" + classNameStr;
            File extClassPatchFile = new File(extPackagePatchFile.getAbsolutePath() + File.separator + extClassStr + ".java");
            try (FileWriter fileWriter = new FileWriter(extClassPatchFile)) {
                fileWriter.append("package " + packageStr + ".ext;\n");
                fileWriter.append("\n");
                fileWriter.append("import " + nameSpace + ";\n");
                fileWriter.append("\n");
                fileWriter.append("public interface " + extClassStr + " extends " + classNameStr + "{");
                fileWriter.append("\n");
                fileWriter.append("}");
            }

            try (FileWriter fileWriter = new FileWriter(extMapperXml)) {
                fileWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                        "<mapper namespace=\"" + packageStr + ".ext." + extClassStr + "\">\n" +
                        "\n" +
                        "</mapper>");
            }


            notify.createNotification("ExtMybatis生成完毕", NotificationType.INFORMATION).notify(event.getProject());

            //不调用这个，会过一段时间才被idea监测到文件生成，体验不好，所以要调用同步刷新
            VirtualFileManager.getInstance().syncRefresh();

        } catch (IOException e) {
            notify.createNotification("ExtMybatis生成异常" + e.getMessage(), NotificationType.ERROR).notify(event.getProject());
        }
    }

    private String getNameSpace(VirtualFile file) {
        try {
            // 创建SAXReader实例
            SAXReader reader = new SAXReader();
            // read()读取指定的XML文档并形成DOM树
            Document document = null;
            document = reader.read(file.getPath());
            // getRootElement()获取根节点
            Element rootEle = document.getRootElement();
            Attribute attribute = rootEle.attribute("namespace");
            if (attribute != null) {
                String namespace = attribute.getData().toString();
                return namespace;
            } else {
                return "";
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        super.update(e);
        VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE);
        if (file.getExtension().equals("xml") && file.getName().contains("Mapper")) {
            e.getPresentation().setEnabledAndVisible(true);
        } else {
            e.getPresentation().setEnabledAndVisible(false);
        }
    }
}
